/*
 * Anemometer.c
 *
 * Created: 17/02/2012 14:22:49
 *  Author: Dani
 * 
 * External clock : PB0
 */ 

#include <avr/io.h>
#include <avr/interrupt.h>
 
uint8_t anemo_counter;
uint32_t seconds;

#define ANEMO_TIMER1_OVF 61936 //65536-3600

ISR (TIMER1_OVF_vect)
{
	seconds++;
	anemo_counter = TCNT0;
	//Reload counter in Timer 0
	TCNT0 = 0;
	// Reload Timer1 to 1 second to next overflow
	TCNT1 = ANEMO_TIMER1_OVF;

}

void ANEMO_InitTimer0()
{
	//External clock falling edge.
	//Normal Mode
	TCCR0 = 0b00000110;
	TCNT0=0;
}

void ANEMO_InitTimer1()
{
  // Normal mode, no waveform generation
  TCCR1A = 0b00000000;
  // Normal mode, clock prescaler PS = 1024
  TCCR1B = 0b00000101;
  // 1 second to next overflow:
  // 3686400/1024/3600 = 1
  TCNT1 = 65536-3600;
  // Enable Timer1 overflow interrupt
  TIMSK |= 0b00000100;
}

void ANEMO_Init()
{
	seconds=0;
	ANEMO_InitTimer0();
	ANEMO_InitTimer1();
}	

uint8_t ANEMO_Read()
{
	cli();
	uint8_t aux=anemo_counter;
	sei();
	return aux;	
}
double ANEMO_FreqToMS(uint8_t freq)
{
	return freq * 0.765;	
}
